package simpleftp.server;

import java.net.ServerSocket;
import java.util.concurrent.*;
import java.io.*;

/**
 * Simple serveur TCP creant des thread pour gerer chaque connexion client.
 * 
 * @author lom
 */
public class FTPServerMain {

	/**
	 * Port d'ecoute.
	 */
	public static final int PORT = 7802;
	/**
	 * Socket serveur d'accueil.
	 */
	private static ServerSocket socketaccueil;

	public static void main(String argv[]) throws Exception {

		// Creating a thread pool to handle multiple connections
		ExecutorService executorService = Executors.newFixedThreadPool(5);

		try {
			socketaccueil = new ServerSocket(PORT);
			System.out.println("Server up and running.");
			FTPServer.setDebug(true);
			while (true) {
				final FTPServer server = new FTPServer(socketaccueil.accept());
				Runnable worker = new Runnable() {

					public void run() {
						try {
							// Listen to what client wants to do
							server.call();
							// Close connection if no exception raised by call
							socketaccueil.close();
						} catch (IOException e) {
							e.printStackTrace();
						}
					}
				};
				// Executing thread pool
				executorService.execute(worker);

			}
		} finally {
			if (socketaccueil != null) {
				socketaccueil.close();
			}
		}
	}
}
